package com.client.job.core.config;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.client.job.core.model.MJobInstance;
import com.client.job.runJob.JobBurstPolicy;
import com.client.job.utils.DataResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSON;
import com.client.job.core.constant.JobUrl;
import com.client.job.core.model.MJob;
import com.client.job.runJob.SystemJobs;

/**
 * 实例化一个请求
 *
 * @author mengxiangzhong
 * @des
 * @date 2021年9月1日
 */
@Configuration
@Slf4j
public class JobServerletRegisterConfig {

    @Bean
    public ServletRegistrationBean<JobClientListController> beanList() {
        return new ServletRegistrationBean<JobClientListController>(new JobClientListController(), JobUrl.client_job_list);
    }

    @Bean
    public ServletRegistrationBean<JobRunOneController> beanRun() {
        return new ServletRegistrationBean<JobRunOneController>(new JobRunOneController(), JobUrl.client_job_run_one);
    }

    @Bean
    public  ServletRegistrationBean<JobRunStatus> runStatus(){
        return new ServletRegistrationBean<JobRunStatus>(new JobRunStatus(), JobUrl.clien_job_status);
    }


    //列表查询
    class JobClientListController extends HttpServlet {
        /**
         * 查询当前服务所有运行的job
         * method: get
         * url: JobUrl.client_job_list
         * param : jobId (空则查询全部，否则查询jobId的)
         */
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String jobId = req.getParameter("jobId");
            log.info("查询当前服务所有运行的job，参数： jobId: {}", jobId);
            List<MJob> res = new ArrayList<>();
            if (jobId == null || jobId.isEmpty()) {
                res.addAll(SystemJobs.getJobs());
            } else {
                res.addAll(SystemJobs.getJobs(jobId));
            }
            buidlDataResult(DataResult.buildSuccess(res), resp);
        }
    }

    /**
     * 运行一次
     */
    class JobRunOneController extends HttpServlet {
        /**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		@SneakyThrows
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String jobName = req.getParameter("jobName");
            if (jobName == null || jobName.isEmpty()) {
                buidlDataResult(DataResult.buildFail("无Job名称"), resp);
            }
            //运行一次
            MJob job = SystemJobs.getJobByName(jobName);
            MJobInstance mJobInstance = MJobInstance.builder().jobName(jobName).sort(job.getCurrentNode()).build();
            JobBurstPolicy.callBack(job, mJobInstance);
            buidlDataResult(DataResult.buildSuccess(), resp);
        }
    }

    /**
     * 查询运行状态
     */
    class JobRunStatus extends HttpServlet {

      
		private static final long serialVersionUID = 1L;

		@Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String jobId = req.getParameter("jobId");
            if(jobId == null || jobId.isEmpty()){
                buidlDataResult(DataResult.buildFail("无Job"), resp);
            }
            if(SystemJobs.getJobs(jobId) != null){
                buidlDataResult(DataResult.buildSuccess(1), resp);
            }else {
                buidlDataResult(DataResult.buildSuccess(0), resp);
            }
        }
    }


    /**
     * 构建同一的返回请求
     *
     * @param obj
     * @param response
     */
    private void buidlDataResult(Object obj, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(obj));
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
